﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PocoConsole
{
    public static class test2
    {

        public static IList GetDdlData<T>(this IEnumerable<T> source, string userParams)
        {
            try
            {
                List<string> otherProperties = userParams.Split(',').ToList();
                Dictionary<string, PropertyInfo> parentPropertyInfo = new Dictionary<string, PropertyInfo>();
                Dictionary<string, Type> parentType = new Dictionary<string, Type>();

                var dynamicObjectList = (from k in source select k).ToList();
                if (dynamicObjectList.Count() > 0)
                {

                    //if parentField exists then system will handle parent property 
                    if (otherProperties.Count > 0)
                    {
                        foreach (string otherProperty in otherProperties)
                        {
                            //get parent field  property info
                            PropertyInfo _info = dynamicObjectList[0].GetType().GetProperty(otherProperty);
                            parentPropertyInfo.Add(otherProperty, _info);
                            //get parent field  propertyType
                            Type pType = Nullable.GetUnderlyingType(_info.PropertyType) ?? _info.PropertyType;
                            parentType.Add(otherProperty, pType);
                        }

                    }
                }
                //return List 
                IList<object> objList = new List<object>();

                foreach (T obj in source)
                {
                    var dynamicObj = new ExpandoObject() as IDictionary<string, Object>;
                    foreach (string otherProperty in otherProperties)
                    {
                        PropertyInfo objPropertyInfo = parentPropertyInfo.FirstOrDefault(m => m.Key == otherProperty).Value;
                        Type objPropertyType = parentType.FirstOrDefault(m => m.Key == otherProperty).Value;
                        Object data = (objPropertyInfo.GetValue(obj, null) == null) ? null : Convert.ChangeType(objPropertyInfo.GetValue(obj, null), objPropertyType, null);
                        dynamicObj.Add(otherProperty, data);
                    }
                    objList.Add(dynamicObj);

                }



                var returnUniqList = objList.Distinct().ToList();

                return returnUniqList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
